package com.turing.post.datatranfer.impl;

import java.math.BigInteger;
import java.util.List;

import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.turing.post.datatranfer.util.CardTradDetail;
import com.turing.post.datatranfer.util.CardTradDetailDao;

/**
 * @author zxp
 * @Jan 27, 2013
 */
@Stateless(mappedName = "datatranfer.impl.CardTradDetailDaoImpl")
@Remote
@Local
public class CardTradDetailDaoImpl implements CardTradDetailDao {
	/**
	 * 实体管理器
	 * 
	 * @see javax.persistence.EntityManager
	 */
	@PersistenceContext
	protected EntityManager _em;

	@SuppressWarnings("unchecked")
	@Override
	public List<CardTradDetail> getCardTradDetailList(Integer page,
			Integer maxResult) {
		Integer start = page * maxResult;
		int end = (page + 1) * maxResult;
		String sql = "SELECT * FROM (SELECT a.*, ROWNUM rn FROM (SELECT * FROM CardTradDetail order by tradtime asc) a WHERE ROWNUM <="
				+ end + ")WHERE rn >" + start;
		Query query = _em.createNativeQuery(sql, CardTradDetail.class);
		return query.getResultList();
	}

	@Override
	public BigInteger getCardTradDetailTotal() {
		Query query = _em
				.createNativeQuery("select nvl(count(*),0) from CardTradDetail");
		return new BigInteger(query.getSingleResult().toString());
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<CardTradDetail> getCardTradDetailList(String transeqno) {
		Query query = _em.createNativeQuery(
				"select * from CardTradDetail where Transeqno='" + transeqno
						+ "'", CardTradDetail.class);
		return query.getResultList();
	}

	// 未开始迁移前最小流水号
	@Override
	public String getMinTranseqno() {
		String sql = "select min(Transeqno) from CardTradDetail";
		Query query = _em.createNativeQuery(sql);
		if (query.getSingleResult() == null) {
			return null;
		}
		return (String) query.getSingleResult();
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<CardTradDetail> getCardTradDetailListByTranDate(String tranDate) {
		String sql = "select * from cardtraddetail t where t.channelid='01' and t.tradtime>=to_date('"+tranDate+" 00:00:00','yyyy-mm-dd hh24:mi:ss') "+
					 "and t.tradtime<=to_date('"+tranDate+" 23:59:59','yyyy-mm-dd hh24:mi:ss') and t.trancode='80' and t.canceltranseqno is null";
		Query query = _em.createNativeQuery(sql, CardTradDetail.class);
		return query.getResultList();
	}
}
